package com.spooky.sync.persistence.db;

import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import android.content.Context;
import android.database.Cursor;
import com.spooky.sync.persistence.dao.CategoryDAO;
import com.spooky.sync.persistence.dao.CategoryDAOBean;
import com.spooky.sync.persistence.entity.BaseEntity;
import com.spooky.sync.persistence.entity.Category;
import com.spooky.sync.persistence.entity.ExpandableNote;

public abstract class NoteExtendedDAOBean<Entity extends BaseEntity> extends ExtendedDAOBean<Entity> {
	protected static final String TABLE_NAME = "note";
	protected static final String COL_TITLE = "n_title";
	protected static final String COL_TEXT = "n_text";
	protected static final String COL_FK_CATEGORY = "n_c_id";
	private Context mContext;
	private CategoryDAO mCategoryDAO;
	private Map<Long, ExpandableNote> mCategories = new TreeMap<Long, ExpandableNote>();

	public NoteExtendedDAOBean(Context context) {
		super(context);
		mContext = context;
	}

	protected NoteExtendedDAOBean() {
		super();
	}

	protected List<ExpandableNote> getAllSpecial() {
		return assembleListSpecial(mSQLiteDatabase.query(getTableName(), getSpecialColumns(), null, null, null, null, null));
	}

	protected abstract void assignSpecial(ExpandableNote obj, Cursor result) throws Exception;

	private List<ExpandableNote> assembleListSpecial(Cursor result) {
		mCategoryDAO = new CategoryDAOBean(mContext);
		ExpandableNote entity = null;
		ExpandableNote category = null;
		if (result.moveToFirst()) {
			do {
				try {
					entity = new ExpandableNote();
					assignSpecial(entity, result);
					category = getCategory(result.getLong(result.getColumnIndexOrThrow(COL_FK_CATEGORY)));
					category.getNote().add(entity);
				} catch (Exception e) {
				}
			} while (result.moveToNext());
		}
		result.close();
		mCategoryDAO.close();
		return new LinkedList<ExpandableNote>(mCategories.values());
	}

	protected abstract String[] getSpecialColumns();

	private ExpandableNote getCategory(Long id) {
		if (!mCategories.containsKey(id)) {
			Category category = mCategoryDAO.find(id);
			mCategories.put(id, new ExpandableNote(category));
		}
		return mCategories.get(id);
	}
}
